package com.bestow.dox4j.component;

import com.bestow.dox4j.IBookmarkHandler;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Component
public class BookmarkHandlerFactory implements ApplicationContextAware {

    private static Logger logger = LoggerFactory.getLogger(BookmarkHandlerFactory.class);
    private Map<String, IBookmarkHandler> handlerMap;

    public BookmarkHandlerFactory() {
    }

    public IBookmarkHandler getHandlerByType(String type) {
        if (StringUtils.isEmpty(type)) {
            throw new IllegalArgumentException();
        } else {
            IBookmarkHandler handler = (IBookmarkHandler)this.handlerMap.get(type);
            if (handler == null) {
                logger.debug("cannot find proper process for type: {}", type);
            }

            return handler;
        }
    }
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.handlerMap = new HashMap();
        Map<String, IBookmarkHandler> beansOfType = applicationContext.getBeansOfType(IBookmarkHandler.class);
        if (beansOfType != null) {
            Iterator var3 = beansOfType.values().iterator();

            while(var3.hasNext()) {
                IBookmarkHandler handler = (IBookmarkHandler)var3.next();
                this.handlerMap.put(handler.getType(), handler);
            }

        }
    }
}
